package com.hao.master;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ScoketServer {

	private ServerSocket server ;
	private String host ;
	private int port ;
	  //创建线程池
    ExecutorService executorService;
 public void init(String host,int port,int num) {
	 this.host= host;
	 this.port=port;
	 executorService = Executors.newFixedThreadPool(num);
	 try {
		this.server = new ServerSocket();
		this.server.bind(new InetSocketAddress(host,port));
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
	 
 }
public void start() {
 		while(true) {
 	    try {
		Socket socket = server.accept();
		executorService.submit(new Runnable() {
				@Override
				public void run() {
					try {
						 //打印当前线程ID
                        System.out.println("当前线程ID："+Thread.currentThread().getId());
						  //a.获得客户端的意图   request 获取输入输出流，并将字节流转换为字符流
					InputStream ins = socket.getInputStream();
			            InputStreamReader insr = new InputStreamReader(ins);
			            BufferedReader br = new BufferedReader(insr); 
			            OutputStream  outs = socket.getOutputStream();
			            OutputStreamWriter outsr = new OutputStreamWriter(outs);
			            BufferedWriter bw = new BufferedWriter(outsr);   
			            //存储读取的数据
			            StringBuilder sb = new StringBuilder();
			            String line = null;
			            //读取数据
			            while((line = br.readLine()) != null){
			                //将数据存储在StringBuilder中
			                sb.append(line);
			            }
			            System.out.println("服务器收到的数据："+sb.toString());
			            bw.write("接收的数据："+sb.toString()+"  服务器已经接收到数据");
			            //将数据发送
			            bw.flush();
			            //关闭流
			            br.close();
			            bw.close();
					}catch (IOException e) {
						throw new RuntimeException(e);
					}finally{
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            }
                        }
					
				}
				 
			});
 	   } catch (IOException e) {
			throw new RuntimeException(e);
		}
		    
             
		}
		
	
	
	
	
}
	
}
